/*
 * Copyright © 2023 广州宏天软件股份有限公司 hotent
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hotent.project.auth.service;

import com.hotent.base.cache.annotation.Cacheable;
import com.hotent.base.cache.annotation.FirstCache;
import com.hotent.base.cache.annotation.SecondaryCache;
import com.hotent.base.constants.CacheKeyConst;
import com.hotent.project.auth.model.BaseUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Primary
public class BaseUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(BaseUserDetailsServiceImpl.class);

    @Resource
    PasswordEncoder passwordEncoder;

    public BaseUserDetailsServiceImpl() {}

    /**
     * 获取用户详情 缓存半个小时，并且每次登录的时候清空
     * 
     * @param username 用户账号
     * @return 用户详情
     * @throws UsernameNotFoundException
     */
    @Cacheable(value = CacheKeyConst.EIP_UC_USER_ACCOUNT, key = "#username", ignoreException = false,
        firstCache = @FirstCache(expireTime = 1800, expireTimeExp = "#expireTime", timeUnit = TimeUnit.SECONDS),
        secondaryCache = @SecondaryCache(expireTime = 1800, expireTimeExp = "#expireTime", preloadTime = 360, forceRefresh = true, timeUnit = TimeUnit.SECONDS))
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // todo 下面是示例代码 需要改造
        logger.info("教工{},正在登录", username);
        BaseUserDetails baseUserDetails = new BaseUserDetails();
        baseUserDetails.setUserId(username);
        baseUserDetails.setAccount(username);
        baseUserDetails.setFullname(username);
        // 默认密码123456
        String encode = passwordEncoder.encode("123456");
        baseUserDetails.setPassword(encode);
        return baseUserDetails;
    }
}
